package com.start.im.core.handler;

import com.alibaba.fastjson2.JSONObject;
import com.start.common.exceptions.StartBusException;
import com.start.im.core.model.StartImConversationMsg;
import com.start.im.core.storage.IStareMsgStorage;
import com.start.ws.connect.StartConnectManager;
import com.start.ws.handler.StartBaseSocketMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.util.List;

@Slf4j
public abstract class StartImGroupMsgHandler<T extends StartImConversationMsg> implements StartBaseSocketMsgHandler<T>, IStartMsg<T>, com.start.im.core.storage.IStareMsgStorage<T> {

    protected IStareMsgStorage<T> storage;

    public StartImGroupMsgHandler(IStareMsgStorage<T> storage) {
        this.storage = storage;
    }

    @Override
    public String handlerMsgType() {
        return "StartImGroupMsg";
    }

    @Override
    public void onReceive(String startUserType, String sendClientType, String sendUserId, T msg, String sendClientMsgId) {
        msg.setSendClientType(sendClientType);
        msg.setSendUserId(sendUserId);
        if (StringUtils.isEmpty(msg.getConversationId())) {
            log.warn("回话id不能为空: sendUserId:{} ,sendClientTYpe:{} ,msg:{}", sendUserId, sendClientType, JSONObject.toJSONString(msg));
            return;
        }
        if (StringUtils.isEmpty(msg.getMsgContent())) {
            log.warn("消息内容不能为空: sendUserId:{} ,sendClientTYpe:{} ,msg:{}", sendUserId, sendClientType, JSONObject.toJSONString(msg));
            return;
        }
        if (!hasGroup(msg.getConversationId())) {
            log.warn("群不存在: msg.getConversationId is null", sendUserId, sendClientType, JSONObject.toJSONString(msg));
            return;
        }
        msg.setSendClientType(sendClientType);
        msg.setSendStartUserType(startUserType);
        msg.setSendUserId(sendUserId);
        sendMsg(msg);
    }

    /**
     * 检查群是否存在
     *
     * @param groupId 群id
     * @return
     */
    public abstract boolean hasGroup(String groupId);

    /**
     * 获取群全部用户id连接key
     *
     * @param groupId 群id
     * @return 用户 用户key=用户类型:用户id  用户类型为：startUserType 值
     */
    public abstract List<String> getGroupUserKeys(String groupId);

    @Override
    public T formatMsg(String msg) {
        Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return JSONObject.parseObject(msg, entityClass);
    }


    @Override
    public void saveMsg(T msg) {
        if (storage == null) {
            log.warn("storage is null group msg Cannot store. msg:{}", JSONObject.toJSONString(msg));
            return;
        }
        msg.setConversationType(handlerMsgType());
        storage.saveMsg(msg);
    }


    /**
     * 发送消息群
     *
     * @param msg
     */
    @Override
    public void sendMsg(T msg) {
        if (StringUtils.isEmpty(msg.getConversationId())) {
            throw new StartBusException("会话id不能为空");
        }
        if (StringUtils.isEmpty(msg.getSendUserId())) {
            throw new StartBusException("发送人不能为空");
        }
        List<String> groupUserKeys = getGroupUserKeys(msg.getConversationId());


        if (groupUserKeys == null || groupUserKeys.isEmpty()) return;

        saveMsg(msg);
        String currentUserKey=StartConnectManager.getUserKey(msg.getSendStartUserType(),msg.getSendUserId());
        for (String userKey : groupUserKeys) {
            if (currentUserKey.equals(userKey)) {
                continue;
            }
            StartConnectManager.getInstance().sendMsg(userKey, JSONObject.toJSONString(msg), null, true);
        }
    }
}
